import React, { useState } from "react"

const UploadCarExcel = () => {
  const [file, setFile] = useState<File | null>(null)
  const [uploading, setUploading] = useState(false)
  const [message, setMessage] = useState("")

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0]
    if (selected && selected.name.endsWith(".xlsx")) {
      setFile(selected)
      setMessage("")
    } else {
      setMessage("请上传 .xlsx 格式的 Excel 文件")
    }
  }

  const handleUpload = async () => {
    if (!file) {
      setMessage("请先选择一个 Excel 文件")
      return
    }

    setUploading(true)
    setMessage("")

    const formData = new FormData()
    formData.append("file", file)

    try {
      const response = await fetch("/api/abroad/import", {
        method: "POST",
        body: formData,
      })

      if (!response.ok) throw new Error("上传失败")
      setMessage("✅ 上传成功！")
    } catch (err) {
      setMessage("❌ 上传失败，请检查文件格式或内容")
    } finally {
      setUploading(false)
    }
  }

  const handleDownloadTemplate = () => {
    fetch("/api/abroad/template")
      .then((res) => {
        if (!res.ok) throw new Error("下载失败")
        return res.blob()
      })
      .then((blob) => {
        setMessage("✅ 下载成功！")
        const url = URL.createObjectURL(blob)
        const a = document.createElement("a")
        a.href = url
        a.download = "车辆导入模板.xlsx"
        a.click()
        URL.revokeObjectURL(url)
        
      })
      .catch(() => {
        setMessage("❌ 模板下载失败")
      })
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4 bg-gray-50">
      <div className="w-full max-w-md bg-white shadow-lg rounded-xl p-6">
        <h2 className="text-2xl font-semibold text-center mb-6">导入车辆采购数据</h2>

        <div className="space-y-4">
          <input
            type="file"
            accept=".xlsx"
            onChange={handleFileChange}
            className="block w-full text-sm text-gray-700 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:bg-blue-100 file:text-blue-700 hover:file:bg-blue-200"
          />

          <div className="flex gap-2">
            <button
              onClick={handleUpload}
              disabled={uploading}
              className={`flex-1 py-2 px-4 rounded text-white ${
                uploading ? "bg-gray-400" : "bg-blue-600 hover:bg-blue-700"
              }`}
            >
              {uploading ? "上传中..." : "上传 Excel"}
            </button>

            <button
              onClick={handleDownloadTemplate}
              className="flex-1 py-2 px-4 rounded border border-gray-300 text-gray-700 hover:bg-gray-100"
            >
              下载模板
            </button>
          </div>

          {message && (
            <p className="text-sm text-center text-red-500 mt-2">{message}</p>
          )}
        </div>
      </div>
    </div>
  )
}

export default UploadCarExcel
